﻿using System;
using System.Xml;
using DataScripter.Scripting;
using DataScripter.Scripting.Output;
using DataScripter.Scripting.Output.Sql.SqlServer;

namespace DataScripter.XmlInterpreter
{
    public class XmlEngineConfiguration
    {
        public XmlEngineConfiguration(string xml)
        {
            var document = new XmlDocument();
            document.LoadXml(xml);
            ScriptOptions = new SqlServerScriptOptions(SqlScriptType.Insert);
            Engine = ConfigureEngine(document);
        }

        public IEngine Engine { get; set; }
        private ScriptOptions ScriptOptions { get; set; }

        private IEngine ConfigureEngine(XmlDocument document)
        {
            if (document == null)
                throw new ArgumentNullException("document");

            var engine = new Engine();

            XmlElement script = document.DocumentElement;
            if (script == null)
            {
                return null;
            }

            IXmlEngineConfigurator configurator = ResolveConfigurator(script, engine);

            return configurator.Configure(engine, document, ScriptOptions);
        }

        private static IXmlEngineConfigurator ResolveConfigurator(XmlElement script, Engine engine)
        {
            string interpreter = script.GetAttribute("XmlInterpreter");
            engine.RegisterType<IXmlEngineConfigurator>(Type.GetType(interpreter));
            return engine.Resolve<IXmlEngineConfigurator>();
        }

        public IScriptResult ProduceScript()
        {
            return Engine.Script(ScriptOptions);
        }

        public void Run()
        {
            Engine.Run();
        }
    }
}